package online.westonline.com.westonline.ui;

import android.app.Dialog;
import android.graphics.Color;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.easy.west.westclient.api.department.bean.DepartMentBean;
import com.easy.west.westclient.api.department.event.FindTopDepartMent;
import com.easy.west.westclient.api.department.event.QueryDepartMentEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.qqtheme.framework.picker.TimePicker;
import online.westonline.com.westonline.MyApplication;
import online.westonline.com.westonline.R;
import online.westonline.com.westonline.adapter.constacts.ChildDepartMentAdapter;
import online.westonline.com.westonline.base.BaseActivity;
import online.westonline.com.westonline.entry.MeetFormBean;
import online.westonline.com.westonline.event.ListClickEvent;
import online.westonline.com.westonline.event.MeetingFormCompeleteEvent;
import online.westonline.com.westonline.utils.CacheUtils;

/**
 * 会议室基本信息表单页面
 */

public class MeetFormActivity extends BaseActivity {


    @BindView(R.id.tv_topbar_title)
    TextView tvTopbarTitle;
    @BindView(R.id.tv_topbar_title_center)
    TextView tvTopbarTitleCenter;
    @BindView(R.id.img_toolbar_menu)
    ImageView imgToolbarMenu;
    @BindView(R.id.tv_topbar_menu)
    TextView tvTopbarMenu;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.edit_meeting_title)
    EditText editMeetingTitle;
    @BindView(R.id.edit_meeting_constacts_name)
    EditText editMeetingConstactsName;
    @BindView(R.id.edit_meeting_constacts_phone)
    EditText editMeetingConstactsPhone;
    @BindView(R.id.tv_meeting_department_select)
    TextView tvMeetingDepartmentSelect;
    @BindView(R.id.ra_department_select)
    RelativeLayout raDepartmentSelect;
    @BindView(R.id.edit_meeting_person_count)
    EditText editMeetingPersonCount;
    @BindView(R.id.edit_meeting_leader_name)
    EditText editMeetingLeaderName;
    @BindView(R.id.tv_meeting_starttime)
    TextView tvMeetingStarttime;
    @BindView(R.id.ra_time_select)
    RelativeLayout raTimeSelect;
    @BindView(R.id.check_private)
    CheckBox checkPrivate;
    @BindView(R.id.ra_check_private)
    RelativeLayout raCheckPrivate;
    @BindView(R.id.btn_form_complete)
    Button btnFormComplete;
    @BindView(R.id.edit_pravite_reason)
    EditText editPraviteReason;
    private String number_person_format;
    private String constacts_name;
    private String constacts_phone;
    private MeetFormBean formBean;
    private Dialog dialog;
    private View view;
    private RecyclerView recyclerView_dialog;
    private ProgressBar progress_load;
    private EditText ed_search_department;
    private List<DepartMentBean> departMentBeanList = new ArrayList<>();
    private ChildDepartMentAdapter departMentAdapter;
    private DepartMentBean departMentBean;
    private TimePicker timePicker;
    private int selecttime;
    private boolean time_select = false;

    @Override
    protected void initview() {
        toolbar.setTitle("会议室申请模板填写");
        tvTopbarMenu.setText("保存为模板");
        tvTopbarMenu.setTextColor(Color.BLACK);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(true);
        //初始化ui
        initui();
        //初始化事件
        initsession();
    }

    private void initsession() {
        //部门选择点击事件
        raDepartmentSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.show();
            }
        });
        //私有复选框
        raCheckPrivate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkPrivate.setChecked(!checkPrivate.isChecked());
            }
        });
        //复选框监听
        checkPrivate.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked)
                {
                    editPraviteReason.setVisibility(View.VISIBLE);
                }
                else
                {
                    editPraviteReason.setVisibility(View.GONE);
                }
            }
        });
        //时间选择点击事件
        raTimeSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timePicker.show();
            }
        });
        timePicker.setOnTimePickListener(new TimePicker.OnTimePickListener() {
            @Override
            public void onTimePicked(String hour, String minute) {
                tvMeetingStarttime.setText(hour + ":" + minute);
                time_select = true;
            }
        });
        //保存基本信息
        btnFormComplete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //对一些必填选项进行判断
                constacts_name = editMeetingConstactsName.getText().toString();
                constacts_phone = editMeetingConstactsPhone.getText().toString();
                number_person_format = editMeetingPersonCount.getText().toString();
                if (TextUtils.isEmpty(constacts_name) || TextUtils.isEmpty(constacts_phone) || TextUtils.isEmpty(number_person_format)) {
                    Snackbar.make(v, "您还有一些必填项没有填", Snackbar.LENGTH_SHORT).show();
                    return;
                }
                if (!time_select) {
                    Snackbar.make(v, "您没有选择开始会议的时间", Snackbar.LENGTH_SHORT).show();
                    return;
                }
                //封装
                formBean.setConstacts_name(constacts_name);
                formBean.setConstacts_phone(constacts_phone);
                formBean.setNumber(Integer.parseInt(number_person_format));
                formBean.setPravite(checkPrivate.isChecked());
                formBean.setStarttime(tvMeetingStarttime.getText().toString());
                formBean.setTitle(editMeetingTitle.getText().toString());
                formBean.setLeader(editMeetingLeaderName.getText().toString());
                formBean.setPraviteReason(editPraviteReason.getText().toString());
                formBean.setTimeType(selecttime);
                if (departMentBean == null) {
                    Snackbar.make(v, "您未选择部门", Snackbar.LENGTH_SHORT).show();
                    return;
                }
                formBean.setDid(departMentBean.getDid());
                formBean.setDepartMentName(departMentBean.getName());
                EventBus.getDefault().post(new MeetingFormCompeleteEvent(formBean));
                finish();
            }
        });
        //保存模板
        tvTopbarMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CacheUtils.getInstance().saveMeetFormGaide(MeetingGaideActivity.class.getSimpleName(),formBean);
            }
        });
    }

    //填充已有数据
    private void initui() {
        //填充dialog
        initdialog();
        //根据已有的数据填充(如果有)
        initform();
    }

    private void initform() {
        if (formBean != null) {
            String title = formBean.getTitle();
            String constacts_name = formBean.getConstacts_name();
            String constacts_phone = formBean.getConstacts_phone();
            String number = String.valueOf(formBean.getNumber());
            String leader = formBean.getLeader();
            String department = formBean.getDepartMentName();
            String starttime = formBean.getStarttime();
            String reason = formBean.getPraviteReason();
            if (!TextUtils.isEmpty(title)) {
                editMeetingTitle.setText(title);
            }
            if (!TextUtils.isEmpty(constacts_name)) {
                editMeetingConstactsName.setText(constacts_name);
            }
            if (!TextUtils.isEmpty(constacts_phone)) {
                editMeetingConstactsPhone.setText(constacts_phone);
            }
            if (!TextUtils.isEmpty(number)) {
                editMeetingPersonCount.setText(number);
            }
            else
            {
                editMeetingPersonCount.setText(null);
            }
            if (!TextUtils.isEmpty(leader)) {
                editMeetingLeaderName.setText(number);
            }
            if (!TextUtils.isEmpty(starttime)) {
                tvMeetingStarttime.setText(starttime);
            }
            if (!TextUtils.isEmpty(department)) {
                tvMeetingDepartmentSelect.setText(department);
            }
            if (!TextUtils.isEmpty(reason))
            {
                editPraviteReason.setText(reason);
            }
                checkPrivate.setChecked(formBean.isPravite());
            if (formBean.isPravite())
            {
                editPraviteReason.setVisibility(View.VISIBLE);
            }
        }
    }

    private void initdialog() {
        dialog = new Dialog(this);
        view = View.inflate(this, R.layout.dialog_department_list, null);
        dialog.setContentView(view);
        dialog.setCancelable(true);
        // 获得当前activity所在的window对象
        Window window = dialog.getWindow();
        WindowManager m = this.getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高度
        WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值
        p.height = (int) (d.getHeight() * 0.75); // 高度设置为屏幕的0.6，根据实际情况调整
        p.width = (int) (d.getWidth() * 0.8); // 宽度设置为屏幕的0.65，根据实际情况调整
        window.setAttributes(p);
        ed_search_department = view.findViewById(R.id.edit_dialog_search_department);
        recyclerView_dialog = view.findViewById(R.id.recyclerView_dialog_department_list);
        progress_load = view.findViewById(R.id.pro_department_loading_state);
        progress_load.setVisibility(View.GONE);
        recyclerView_dialog.setLayoutManager(new LinearLayoutManager(this));
        recyclerView_dialog.setAdapter(departMentAdapter);
        //对输入框进行监听
        ed_search_department.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length()>=1)
                {
                    //清空列表
                    recyclerView_dialog.removeAllViews();
                    //展示进度条
                    progress_load.setVisibility(View.VISIBLE);
                    //调用搜索接口
                    MyApplication.getClient().queryDepartment(s.toString());
                }
            }
        });

    }

    @Override
    protected void initdata() {
        formBean = CacheUtils.getInstance().getMeetFormBean(getIntent().getExtras().getInt("mid"));
        if (formBean == null) {
            formBean = new MeetFormBean();
        }
        selecttime = getIntent().getExtras().getInt("time");
        //请求部门列表
        //MyApplication.getClient().findallParentDepartMent();
        //初始化变量
        departMentAdapter = new ChildDepartMentAdapter();
        //初始化时间框
        timePicker = new TimePicker(this);
        if (selecttime == 1) {
            timePicker.setRangeStart(8, 30);
            timePicker.setRangeEnd(12, 0);
        }
        if (selecttime == 2) {
            timePicker.setRangeStart(14, 0);
            timePicker.setRangeEnd(18, 0);
        }
        if (selecttime == 3) {
            timePicker.setRangeStart(18, 30);
            timePicker.setRangeEnd(22, 0);
        }
        if (selecttime == 4) {
            timePicker.setRangeStart(8, 30);
            timePicker.setRangeEnd(22, 0);
        }
    }

    @Override
    protected int setlayout() {
        return R.layout.activity_meet_form;
    }

    @Override
    public void finish() {
        super.finish();
    }

    /**
     * 得到部门列表
     *
     * @param eva
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getSearchdepartment(QueryDepartMentEvent eva) {
        if (eva.isOk()) {
            progress_load.setVisibility(View.GONE);
            departMentBeanList = eva.getBean().getData();
            configRecyclerview();
        }
    }

    /**
     * 选中了部门
     * @param eva
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getNowSelectDepartMent(ListClickEvent eva) {
        departMentBean = eva.getDepartMentBean();
        tvMeetingDepartmentSelect.setText(departMentBean.getName());
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    private void configRecyclerview() {
        departMentAdapter.setDepartMentBeanList(departMentBeanList);
        departMentAdapter.notifyDataSetChanged();
    }



}
